<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>20-定型数组 | 小黑博客</title><meta name="keywords" content="JavaScript,JavaScript高级程序设计第四版"><meta name="author" content="BluesYoung-web"><meta name="copyright" content="BluesYoung-web"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="ECMAScript 为了提升向原生库传输数据的效率而新增的结构 实质上是一种包含特殊数值类型的数组     历史        WebGL早期版本 JavaScript 数组与原生数组之间不匹配，出现性能问题     Mozilla 为解决这个问题而实现了 CanvasFloatArray     最终，CanvasFloatArray 变成了 Float32Array，也就是今天定型数组中可">
<meta property="og:type" content="article">
<meta property="og:title" content="20-定型数组">
<meta property="og:url" content="https://bluesyoung-web.gitee.io/blog/2021-01-04-20-%E5%AE%9A%E5%9E%8B%E6%95%B0%E7%BB%84.html">
<meta property="og:site_name" content="小黑博客">
<meta property="og:description" content="ECMAScript 为了提升向原生库传输数据的效率而新增的结构 实质上是一种包含特殊数值类型的数组     历史        WebGL早期版本 JavaScript 数组与原生数组之间不匹配，出现性能问题     Mozilla 为解决这个问题而实现了 CanvasFloatArray     最终，CanvasFloatArray 变成了 Float32Array，也就是今天定型数组中可">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://bluesyoung-web.gitee.io/blog/img/hbs.png">
<meta property="article:published_time" content="2021-01-04T06:15:08.000Z">
<meta property="article:modified_time" content="2021-08-29T11:36:10.269Z">
<meta property="article:author" content="BluesYoung-web">
<meta property="article:tag" content="JavaScript">
<meta property="article:tag" content="JavaScript高级程序设计第四版">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://bluesyoung-web.gitee.io/blog/img/hbs.png"><link rel="shortcut icon" href="/blog/img/favicon.png"><link rel="canonical" href="https://bluesyoung-web.gitee.io/blog/2021-01-04-20-%E5%AE%9A%E5%9E%8B%E6%95%B0%E7%BB%84"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="stylesheet" href="/blog/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/blog/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: BluesYoung-web","link":"链接: ","source":"来源: 小黑博客","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#121212","position":"top-right"},
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isanchor: true
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '20-定型数组',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: false,
  postUpdate: '2021-08-29 19:36:10'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="/blog/css/background.css"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/sviptzk/HexoStaticFile@latest/Hexo/css/custom.min.css"></link><meta name="generator" content="Hexo 5.4.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/blog/img/lufei_siwangningshi.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data is-center"><div class="data-item"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">153</div></a></div><div class="data-item"><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">54</div></a></div><div class="data-item"><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">48</div></a></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/blog/img/hbs.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/blog/">小黑博客</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">20-定型数组</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-01-04T06:15:08.000Z" title="发表于 2021-01-04 14:15:08">2021-01-04</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-08-29T11:36:10.269Z" title="更新于 2021-08-29 19:36:10">2021-08-29</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">学习笔记</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/JavaScript%E9%AB%98%E7%BA%A7%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/">JavaScript高级程序设计</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/JavaScript%E9%AB%98%E7%BA%A7%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/%E7%AC%AC06%E7%AB%A0%E2%80%94%E2%80%94%E9%9B%86%E5%90%88%E5%BC%95%E7%94%A8%E7%B1%BB%E5%9E%8B/">第06章——集合引用类型</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">1.5k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>5分钟</span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><ul>
<li><code>ECMAScript</code> 为了提升向原生库传输数据的效率而新增的结构</li>
<li>实质上是一种包含特殊数值类型的数组</li>
</ul>
<div id="archive">
  <div class="article-sort-title">历史</div>
  <div class="article-sort">
    <div class="article-sort-item year">WebGL早期版本 JavaScript 数组与原生数组之间不匹配，出现性能问题</div>
    <div class="article-sort-item year">Mozilla 为解决这个问题而实现了 CanvasFloatArray</div>
    <div class="article-sort-item year">最终，CanvasFloatArray
变成了 Float32Array，也就是今天定型数组中可用的第一个“类型”</div>
  </div>
</div>



<h2 id="ArrayBuffer"><a href="#ArrayBuffer" class="headerlink" title="ArrayBuffer"></a><code>ArrayBuffer</code></h2><ul>
<li><code>Float32Array </code>实际上是一种“<strong>视图</strong>”，可以允许 <code>JavaScript </code>运行时访问一块名为 <code>ArrayBuffer </code>的预分配内存</li>
<li><code>ArrayBuffer </code>是<strong>所有定型数组及视图引用的基本单位</strong></li>
<li><code>ArrayBuffer </code>一经创建就<strong>不能再调整大小</strong>。不过，可以使用<code> slice()</code>复制其全部或部分到一个新实例中</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> buf = <span class="keyword">new</span> <span class="built_in">ArrayBuffer</span>(<span class="number">16</span>); <span class="comment">// 在内存中分配 16 字节(128 位)</span></span><br><span class="line"><span class="built_in">console</span>.log(buf.byteLength);     <span class="comment">// 16</span></span><br><span class="line"><span class="keyword">const</span> buf2 = buf1.slice(<span class="number">4</span>, <span class="number">12</span>);</span><br><span class="line">alert(buf2.byteLength);          <span class="comment">// 8 </span></span><br></pre></td></tr></table></figure>

<h3 id="与-c-的-malloc-函数对比"><a href="#与-c-的-malloc-函数对比" class="headerlink" title="与 c++ 的 malloc 函数对比"></a>与 <code>c++</code> 的 <code>malloc</code> 函数对比</h3><table>
<thead>
<tr>
<th>—</th>
<th><code>malloc</code></th>
<th><code>ArrayBuffer</code></th>
</tr>
</thead>
<tbody><tr>
<td>分配失败</td>
<td>返回 <code>null</code> 指针</td>
<td>抛出错误</td>
</tr>
<tr>
<td>分配内存大小</td>
<td>只受可寻址系统内存限制</td>
<td>不能超过<code>Number.MAX_SAFE_INTEGER</code>（2<sup>53</sup> - 1）</td>
</tr>
<tr>
<td>初始化</td>
<td>不会初始化实际的地址</td>
<td>将所有二进制位初始化为 0</td>
</tr>
<tr>
<td>垃圾回收</td>
<td>需要手动回收</td>
<td>自动回收</td>
</tr>
</tbody></table>
<h2 id="DataView"><a href="#DataView" class="headerlink" title="DataView"></a><code>DataView</code></h2><ul>
<li>允许读写 <code>ArrayBuffer</code> 的视图</li>
<li>专为文件 <code>I/O</code> 与网络 <code>I/O</code> 设计</li>
<li>支持对缓冲数据的高度控制，但是性能也较差</li>
<li>对内容没有任何预设，也不能迭代</li>
<li>必须在对已有的 <code>ArrayBuffer </code>读取或写入时才能创建 <code>DataView </code>实例</li>
<li>这个实例可以使用全部或部分 <code>ArrayBuffer</code>，且维护着对该缓冲实例的引用，以及视图在缓冲中开始的位置</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> buf = <span class="keyword">new</span> <span class="built_in">ArrayBuffer</span>(<span class="number">16</span>);</span><br><span class="line"><span class="comment">// DataView 默认使用整个 ArrayBuffer</span></span><br><span class="line"><span class="keyword">const</span> fullDataView = <span class="keyword">new</span> <span class="built_in">DataView</span>(buf);</span><br><span class="line">alert(fullDataView.byteOffset); <span class="comment">// 0</span></span><br><span class="line">alert(fullDataView.byteLength); <span class="comment">// 16</span></span><br><span class="line">alert(fullDataView.buffer === buf); <span class="comment">// true</span></span><br><span class="line"><span class="comment">// 构造函数接收一个可选的字节偏移量和字节长度</span></span><br><span class="line"><span class="comment">// byteOffset=0 表示视图从缓冲起点开始</span></span><br><span class="line"><span class="comment">// byteLength=8 限制视图为前 8 个字节</span></span><br><span class="line"><span class="keyword">const</span> firstHalfDataView = <span class="keyword">new</span> <span class="built_in">DataView</span>(buf, <span class="number">0</span>, <span class="number">8</span>);</span><br><span class="line">alert(firstHalfDataView.byteOffset); <span class="comment">// 0</span></span><br><span class="line">alert(firstHalfDataView.byteLength); <span class="comment">// 8</span></span><br><span class="line">alert(firstHalfDataView.buffer === buf); <span class="comment">// true</span></span><br><span class="line"><span class="comment">// 如果不指定，则 DataView 会使用剩余的缓冲</span></span><br><span class="line"><span class="comment">// byteOffset=8 表示视图从缓冲的第 9 个字节开始</span></span><br><span class="line"><span class="comment">// byteLength 未指定，默认为剩余缓冲</span></span><br><span class="line"><span class="keyword">const</span> secondHalfDataView = <span class="keyword">new</span> <span class="built_in">DataView</span>(buf, <span class="number">8</span>);</span><br><span class="line">alert(secondHalfDataView.byteOffset); <span class="comment">// 8 </span></span><br><span class="line">alert(secondHalfDataView.byteLength); <span class="comment">// 8</span></span><br><span class="line">alert(secondHalfDataView.buffer === buf); <span class="comment">// true </span></span><br></pre></td></tr></table></figure>

<h3 id="ElementType"><a href="#ElementType" class="headerlink" title="ElementType"></a><code>ElementType</code></h3><table>
<thead>
<tr>
<th><code>ElementType</code></th>
<th><code>byteLength</code></th>
<th><code>des</code></th>
<th><code>in C lang</code></th>
<th><code>range</code></th>
</tr>
</thead>
<tbody><tr>
<td><code>Int8</code></td>
<td>1</td>
<td>8 位有符号整数</td>
<td>signed char</td>
<td>[-128, 127]</td>
</tr>
<tr>
<td><code>Uint8</code></td>
<td>1</td>
<td>8 位无符号整数</td>
<td>unsigned char</td>
<td>[0, 255]</td>
</tr>
<tr>
<td><code>Int16</code></td>
<td>2</td>
<td>16 位有符号整数</td>
<td>short</td>
<td>[-32768, 32767]</td>
</tr>
<tr>
<td><code>Uint16</code></td>
<td>2</td>
<td>16 位无符号整数</td>
<td>unsigned short</td>
<td>[0, 65535]</td>
</tr>
<tr>
<td><code>Int32</code></td>
<td>4</td>
<td>32 位有符号整数</td>
<td>int</td>
<td>[-2147483648, 2147483647]</td>
</tr>
<tr>
<td><code>Uint32</code></td>
<td>4</td>
<td>32 位无符号整数</td>
<td>unsigned int</td>
<td>[0, 4294967295]</td>
</tr>
<tr>
<td><code>Float32</code></td>
<td>4</td>
<td>32 位 IEEE-754 浮点数</td>
<td>float</td>
<td>[-3.4e+38, 3.4e+38]</td>
</tr>
<tr>
<td><code>Float64</code></td>
<td>8</td>
<td>64 位 IEEE-754 浮点数</td>
<td>double</td>
<td>[-1.7e+308, 1.7e+308]</td>
</tr>
</tbody></table>
<h3 id="字节序-大小端"><a href="#字节序-大小端" class="headerlink" title="字节序(大小端)"></a><code>字节序(大小端)</code></h3><ul>
<li><code>DataView</code> 默认大端，所有<code>API</code>可选参数传入<code>true</code>变为小端</li>
</ul>
<h4 id="大端字节序"><a href="#大端字节序" class="headerlink" title="大端字节序"></a>大端字节序</h4><ul>
<li>也叫“网络字节序”</li>
<li>从左到右存储/读取</li>
</ul>
<h4 id="小端字节序"><a href="#小端字节序" class="headerlink" title="小端字节序"></a>小端字节序</h4><ul>
<li>从右到左存储/读取</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 在内存中分配两个字节并声明一个 DataView</span></span><br><span class="line"><span class="keyword">const</span> buf = <span class="keyword">new</span> <span class="built_in">ArrayBuffer</span>(<span class="number">2</span>);</span><br><span class="line"><span class="keyword">const</span> view = <span class="keyword">new</span> <span class="built_in">DataView</span>(buf);</span><br><span class="line"><span class="comment">// 填充缓冲，让第一位和最后一位都是 1</span></span><br><span class="line">view.setUint8(<span class="number">0</span>, <span class="number">0x80</span>); <span class="comment">// 设置最左边的位等于 1</span></span><br><span class="line">view.setUint8(<span class="number">1</span>, <span class="number">0x01</span>); <span class="comment">// 设置最右边的位等于 1</span></span><br><span class="line"><span class="comment">// 缓冲内容（为方便阅读，人为加了空格）</span></span><br><span class="line"><span class="comment">// 0x8 0x0 0x0 0x1</span></span><br><span class="line"><span class="comment">// 1000 0000 0000 0001</span></span><br><span class="line"><span class="comment">// 按大端字节序读取 Uint16</span></span><br><span class="line"><span class="comment">// 0x80 是高字节，0x01 是低字节</span></span><br><span class="line"><span class="comment">// 0x8001 = 2^15 + 2^0 = 32768 + 1 = 32769</span></span><br><span class="line">alert(view.getUint16(<span class="number">0</span>)); <span class="comment">// 32769</span></span><br><span class="line"><span class="comment">// 按小端字节序读取 Uint16</span></span><br><span class="line"><span class="comment">// 0x01 是高字节，0x80 是低字节</span></span><br><span class="line"><span class="comment">// 0x0180 = 2^8 + 2^7 = 256 + 128 = 384</span></span><br><span class="line">alert(view.getUint16(<span class="number">0</span>, <span class="literal">true</span>)); <span class="comment">// 384</span></span><br><span class="line"><span class="comment">// 按大端字节序写入 Uint16</span></span><br><span class="line">view.setUint16(<span class="number">0</span>, <span class="number">0x0004</span>);</span><br><span class="line"><span class="comment">// 缓冲内容（为方便阅读，人为加了空格）</span></span><br><span class="line"><span class="comment">// 0x0 0x0 0x0 0x4</span></span><br><span class="line"><span class="comment">// 0000 0000 0000 0100</span></span><br><span class="line">alert(view.getUint8(<span class="number">0</span>)); <span class="comment">// 0</span></span><br><span class="line">alert(view.getUint8(<span class="number">1</span>)); <span class="comment">// 4</span></span><br><span class="line"><span class="comment">// 按小端字节序写入 Uint16</span></span><br><span class="line">view.setUint16(<span class="number">0</span>, <span class="number">0x0002</span>, <span class="literal">true</span>);</span><br><span class="line"><span class="comment">// 缓冲内容（为方便阅读，人为加了空格）</span></span><br><span class="line"><span class="comment">// 0x0 0x2 0x0 0x0</span></span><br><span class="line"><span class="comment">// 0000 0010 0000 0000</span></span><br><span class="line">alert(view.getUint8(<span class="number">0</span>)); <span class="comment">// 2</span></span><br><span class="line">alert(view.getUint8(<span class="number">1</span>)); <span class="comment">// 0</span></span><br></pre></td></tr></table></figure>

<h3 id="边界情况"><a href="#边界情况" class="headerlink" title="边界情况"></a>边界情况</h3><ul>
<li>读取或写入超出缓冲区范围的值都会报错</li>
<li>写入时会尽最大努力把一个值转换为适当的类型，后备值为 0，如果无法转换则报错(自动调用对应的 <code>parse</code>)</li>
</ul>
<h2 id="定型数组"><a href="#定型数组" class="headerlink" title="定型数组"></a>定型数组</h2><ul>
<li>另一种形式的 <code>ArrayBuffer</code> 视图</li>
<li>特定于一种<code>ElementType</code>且遵循系统原生字节序</li>
<li>提供了适用面更广的 <code>API</code> 和更高的性能</li>
<li>为了提高与 <code>WebGL </code>等原生库交换二进制数据的效率而设计，速度极快</li>
</ul>
<h3 id="创建方式"><a href="#创建方式" class="headerlink" title="创建方式"></a>创建方式</h3><ul>
<li>读取已有的缓冲</li>
<li>使用自有缓冲</li>
<li>填充可迭代结构</li>
<li>填充基于任意类型的定型数组</li>
<li><code>&lt;ElementType&gt;.from()</code></li>
<li><code>&lt;ElementType&gt;.of()</code></li>
</ul>
<h3 id="与普通数组相同属性及方法"><a href="#与普通数组相同属性及方法" class="headerlink" title="与普通数组相同属性及方法"></a>与普通数组相同属性及方法</h3><ul>
<li><code>[]</code></li>
<li><code>copyWithin()</code></li>
<li><code>entries()</code></li>
<li><code>every()</code></li>
<li><code>fill()</code></li>
<li><code>filter()</code></li>
<li><code>find()</code></li>
<li><code>findIndex()</code></li>
<li><code>forEach()</code></li>
<li><code>indexOf()</code></li>
<li><code>join()</code></li>
<li><code>keys()</code></li>
<li><code>lastIndexOf()</code></li>
<li><code>length</code></li>
<li><code>map()</code></li>
<li><code>reduce()</code></li>
<li><code>reduceRight()</code></li>
<li><code>reverse()</code></li>
<li><code>slice()</code></li>
<li><code>some()</code></li>
<li><code>sort()</code></li>
<li><code>toLocaleString()</code></li>
<li><code>toString()</code></li>
<li><code>values()</code></li>
<li><code>for-of</code></li>
<li><code>...</code></li>
<li><code>concat()</code></li>
<li><code>pop()</code></li>
<li><code>shift()</code></li>
<li><code>splice()</code></li>
<li><code>unshift()</code></li>
</ul>
<h3 id="新增方法"><a href="#新增方法" class="headerlink" title="新增方法"></a>新增方法</h3><ul>
<li><code>set()</code> 从提供的数组或定型数组中把值复制到当前定型数组中指定的索引位置</li>
<li><code>subarray()</code> 基于从原始定型数组中复制的值返回一个新定型数组</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 创建长度为 8 的 int16 数组</span></span><br><span class="line"><span class="keyword">const</span> container = <span class="keyword">new</span> <span class="built_in">Int16Array</span>(<span class="number">8</span>);</span><br><span class="line"><span class="comment">// 把定型数组复制为前 4 个值</span></span><br><span class="line"><span class="comment">// 偏移量默认为索引 0</span></span><br><span class="line">container.set(<span class="built_in">Int8Array</span>.of(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>));</span><br><span class="line"><span class="built_in">console</span>.log(container); <span class="comment">// [1,2,3,4,0,0,0,0]</span></span><br><span class="line"><span class="comment">// 把普通数组复制为后 4 个值</span></span><br><span class="line"><span class="comment">// 偏移量 4 表示从索引 4 开始插入</span></span><br><span class="line">container.set([<span class="number">5</span>,<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>], <span class="number">4</span>);</span><br><span class="line"><span class="built_in">console</span>.log(container); <span class="comment">// [1,2,3,4,5,6,7,8]</span></span><br><span class="line"><span class="comment">// 溢出会抛出错误</span></span><br><span class="line">container.set([<span class="number">5</span>,<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>], <span class="number">7</span>);</span><br><span class="line"><span class="comment">// RangeError </span></span><br><span class="line"></span><br><span class="line"><span class="comment">/////////////////////////////////////////////</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> source = <span class="built_in">Int16Array</span>.of(<span class="number">2</span>, <span class="number">4</span>, <span class="number">6</span>, <span class="number">8</span>);</span><br><span class="line"><span class="comment">// 把整个数组复制为一个同类型的新数组</span></span><br><span class="line"><span class="keyword">const</span> fullCopy = source.subarray();</span><br><span class="line"><span class="built_in">console</span>.log(fullCopy); <span class="comment">// [2, 4, 6, 8]</span></span><br><span class="line"><span class="comment">// 从索引 2 开始复制数组</span></span><br><span class="line"><span class="keyword">const</span> halfCopy = source.subarray(<span class="number">2</span>);</span><br><span class="line"><span class="built_in">console</span>.log(halfCopy); <span class="comment">// [6, 8]</span></span><br><span class="line"><span class="comment">// 从索引 1 开始复制到索引 3</span></span><br><span class="line"><span class="keyword">const</span> partialCopy = source.subarray(<span class="number">1</span>, <span class="number">3</span>);</span><br><span class="line"><span class="built_in">console</span>.log(partialCopy); <span class="comment">// [4, 6] </span></span><br></pre></td></tr></table></figure>

</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">BluesYoung-web</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://bluesyoung-web.gitee.io/blog/2021-01-04-20-%E5%AE%9A%E5%9E%8B%E6%95%B0%E7%BB%84.html">https://bluesyoung-web.gitee.io/blog/2021-01-04-20-%E5%AE%9A%E5%9E%8B%E6%95%B0%E7%BB%84.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://BluesYoung-web.gitee.io/blog" target="_blank">小黑博客</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/blog/tags/JavaScript/">JavaScript</a><a class="post-meta__tags" href="/blog/tags/JavaScript%E9%AB%98%E7%BA%A7%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1%E7%AC%AC%E5%9B%9B%E7%89%88/">JavaScript高级程序设计第四版</a></div><div class="post_share"></div></div><div class="post-reward"><div class="reward-button button--animated"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/blog/img/wx.png" target="_blank"><img class="post-qr-code-img" src="/blog/img/wx.png" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="/blog/img/zfb.jpg" target="_blank"><img class="post-qr-code-img" src="/blog/img/zfb.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/blog/2020-12-28-01-历史回顾.html" title="01-历史回顾"><img class="cover" src="/blog/img/hbs.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-12-28</div><div class="title">01-历史回顾</div></div></a></div><div><a href="/blog/2020-12-28-03-script元素.html" title="03-script元素"><img class="cover" src="/blog/img/hbs.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-12-28</div><div class="title">03-script元素</div></div></a></div><div><a href="/blog/2020-12-28-02-实现.html" title="02-实现"><img class="cover" src="/blog/img/hbs.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-12-28</div><div class="title">02-实现</div></div></a></div><div><a href="/blog/2020-12-28-04-文档模式.html" title="04-文档模式"><img class="cover" src="/blog/img/hbs.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-12-28</div><div class="title">04-文档模式</div></div></a></div><div><a href="/blog/2020-12-28-05-语法.html" title="05-语法"><img class="cover" src="/blog/img/hbs.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-12-28</div><div class="title">05-语法</div></div></a></div><div><a href="/blog/2020-12-28-06-变量声明.html" title="06-变量声明"><img class="cover" src="/blog/img/hbs.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-12-28</div><div class="title">06-变量声明</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/blog/img/lufei_siwangningshi.jpg" onerror="this.onerror=null;this.src='/blog/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">BluesYoung-web</div><div class="author-info__description">一枚不善言辞的技术宅</div></div><div class="card-info-data is-center"><div class="card-info-data-item"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">153</div></a></div><div class="card-info-data-item"><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">54</div></a></div><div class="card-info-data-item"><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">48</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://gitee.com/BluesYoung-web"><i class="fab fa-gitee"></i><span>点个小星星吧</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/BluesYoung-web" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="mailto:15171255945@163.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a></div></div><div class="sticky_layout"><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/blog/2021-08-24-%E7%A7%BB%E5%8A%A8%E7%AB%AF%E8%BD%AF%E9%94%AE%E7%9B%98%E5%AF%BC%E8%87%B4%E5%B8%83%E5%B1%80%E9%94%99%E4%B9%B1.html" title="移动端软键盘导致布局错乱"><img src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="移动端软键盘导致布局错乱"/></a><div class="content"><a class="title" href="/blog/2021-08-24-%E7%A7%BB%E5%8A%A8%E7%AB%AF%E8%BD%AF%E9%94%AE%E7%9B%98%E5%AF%BC%E8%87%B4%E5%B8%83%E5%B1%80%E9%94%99%E4%B9%B1.html" title="移动端软键盘导致布局错乱">移动端软键盘导致布局错乱</a><time datetime="2021-08-24T10:01:20.000Z" title="发表于 2021-08-24 18:01:20">2021-08-24</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2021-08-16-Linux%E5%AE%89%E8%A3%85you-get.html" title="Linux安装you-get"><img src="/blog/img/shumeipai_cover.jpg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="Linux安装you-get"/></a><div class="content"><a class="title" href="/blog/2021-08-16-Linux%E5%AE%89%E8%A3%85you-get.html" title="Linux安装you-get">Linux安装you-get</a><time datetime="2021-08-16T08:07:31.000Z" title="发表于 2021-08-16 16:07:31">2021-08-16</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2021-08-16-git%E5%88%A0%E9%99%A4%E8%BF%9C%E7%A8%8B%E4%BB%93%E5%BA%93%E7%9A%84%E6%8F%90%E4%BA%A4.html" title="git删除远程仓库的提交"><img src="/blog/img/skill.jpg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="git删除远程仓库的提交"/></a><div class="content"><a class="title" href="/blog/2021-08-16-git%E5%88%A0%E9%99%A4%E8%BF%9C%E7%A8%8B%E4%BB%93%E5%BA%93%E7%9A%84%E6%8F%90%E4%BA%A4.html" title="git删除远程仓库的提交">git删除远程仓库的提交</a><time datetime="2021-08-16T07:52:02.000Z" title="发表于 2021-08-16 15:52:02">2021-08-16</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2021-08-13-%E5%B0%86pad%E6%89%A9%E5%B1%95%E4%B8%BA%E7%94%B5%E8%84%91%E7%9A%84%E5%89%AF%E5%B1%8F.html" title="将pad扩展为电脑的副屏"><img src="/blog/img/skill.jpg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="将pad扩展为电脑的副屏"/></a><div class="content"><a class="title" href="/blog/2021-08-13-%E5%B0%86pad%E6%89%A9%E5%B1%95%E4%B8%BA%E7%94%B5%E8%84%91%E7%9A%84%E5%89%AF%E5%B1%8F.html" title="将pad扩展为电脑的副屏">将pad扩展为电脑的副屏</a><time datetime="2021-08-13T11:44:04.000Z" title="发表于 2021-08-13 19:44:04">2021-08-13</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2021-08-11-Linux%E5%90%AF%E7%94%A8SSH%E6%9C%8D%E5%8A%A1.html" title="Linux启用SSH服务"><img src="/blog/img/shumeipai_cover.jpg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="Linux启用SSH服务"/></a><div class="content"><a class="title" href="/blog/2021-08-11-Linux%E5%90%AF%E7%94%A8SSH%E6%9C%8D%E5%8A%A1.html" title="Linux启用SSH服务">Linux启用SSH服务</a><time datetime="2021-08-11T10:50:04.000Z" title="发表于 2021-08-11 18:50:04">2021-08-11</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2021 By BluesYoung-web</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/blog/js/utils.js"></script><script src="/blog/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script src="/blog/js/search/local-search.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"><script>if (document.getElementsByClassName('mermaid').length) {
  if (window.mermaidJsLoad) mermaid.init()
  else {
    getScript('https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js').then(() => {
      window.mermaidJsLoad = true
      mermaid.initialize({
        theme: 'default',
      })
      false && mermaid.init()
    })
  }
}</script></div><script src="https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js"></script> <script src="/blog/js/xkTool.js"></script> <script src="/blog/js/mySelf.js"></script><canvas class="fireworks" mobile="false"></canvas><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/fireworks.min.js"></script><script id="canvas_nest" defer="defer" color="0,0,255" opacity="0.7" zIndex="-1" count="99" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-nest.min.js"></script></div></body></html>